package com.ywgt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ywgt.pojo.Category;
import com.ywgt.mapper.CategoryMapper;
import com.ywgt.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ywgt.util.ResponseUtil;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 类目表 服务实现类
 * </p>
 *
 * @author yiping
 * @since 2021-03-13
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> getMenu() {
        return baseMapper.selectMenu();
    }

    @Override
    public Page<Category> getCategories(String name, Integer id, String sort, String order, int page, int limit) {
        PageHelper.startPage(page,limit);
        return baseMapper.selectCategories(name,id,sort,order);
    }

    @Override
    public List<Category> getLevel1() {
        LambdaQueryWrapper<Category> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Category::getLevel,"L1");
        wrapper.eq(Category::getDeleted,0);
        PageHelper.startPage(1,9);
        return this.list(wrapper);
    }

    @Override
    public Object getCategoriesById(Integer id) {
        Category cur = this.getById(id);
        Category parent;
        List<Category> children;
        if(cur.getPid()==0){
            parent=cur;
            LambdaQueryWrapper<Category> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(Category::getPid,cur.getId());
            wrapper.eq(Category::getDeleted,0);
            children = this.list(wrapper);
            cur=children.size()>0?children.get(0):cur;
        }else {
            LambdaQueryWrapper<Category> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(Category::getPid,cur.getPid());
            wrapper.eq(Category::getDeleted,0);
            children = this.list(wrapper);
            wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(Category::getId,cur.getPid());
            wrapper.eq(Category::getDeleted,0);
            parent=this.getOne(wrapper);
        }
        Map<String,Object> data=new HashMap<>();
        data.put("currentCategory", cur);
        data.put("parentCategory", parent);
        data.put("brotherCategory", children);
        return ResponseUtil.ok(data);
    }
}
